#import "AudioDataPlugin.h"
#import "AudioRecorder.h"

@interface AudioDataPlugin()<FlutterStreamHandler>

@property (nonatomic,strong) FlutterEventSink sink;
@property (nonatomic,strong) AudioRecorder* audioRecorder;

@end


@implementation AudioDataPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:@"audio_data"
            binaryMessenger:[registrar messenger]];
  AudioDataPlugin* instance = [[AudioDataPlugin alloc] init];
  [registrar addMethodCallDelegate:instance channel:channel];
    
    FlutterEventChannel * event = [FlutterEventChannel eventChannelWithName:@"audio_data_eventChannel" binaryMessenger:registrar.messenger];
    [event setStreamHandler:instance];
}

- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
                                       eventSink:(FlutterEventSink)events{
    
    self.sink = events;
    return nil;
}
- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments{
    return nil;
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([@"getPlatformVersion" isEqualToString:call.method]) {
    result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
  } else if ([@"startRecord" isEqualToString:call.method]) {
      if (self.audioRecorder != nil) {
          NSLog(@"%@",@"正在录音");
          return;
      }
      
      self.audioRecorder = [[AudioRecorder alloc] init];
      self.audioRecorder.sink = self.sink;
      [self.audioRecorder startRecord];
      
  } else if ([@"stopRecord" isEqualToString:call.method]) {
      [self.audioRecorder endRecord];
      self.audioRecorder = nil;
  }
  else {
    result(FlutterMethodNotImplemented);
  }
}


@end
